package com.guli.teacher.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guli.teacher.entity.EduSubject;
import com.guli.teacher.entity.vo.OneSubject;
import com.guli.teacher.entity.vo.TwoSubject;
import com.guli.teacher.mapper.EduSubjectMapper;
import com.guli.teacher.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author guli
 * @since 2020-05-28
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public List<String> importEXCL(MultipartFile file) {

        //  存储错误信息集合
        List<String> meg = new ArrayList<>();

        try {
            // 1 获取文件的流
            InputStream inputStream = file.getInputStream();

            // 2 根据这流创建一个workBook
            Workbook workbook = new HSSFWorkbook(inputStream);

            // 3 获取Sheet，getSheetAt（0）
            Sheet sheet = workbook.getSheetAt(0);

            // 4 根据这Sheet获取行数
            int lastRowNum = sheet.getLastRowNum();
            if (lastRowNum <= 1){
                meg.add("请填写数据");
                return meg;
            }
            // 5 遍历行
            for (int rowNum = 1; rowNum < lastRowNum; rowNum++){
                Row row = sheet.getRow(rowNum);
                // 6 获取每一行中第一列：一级分类
                Cell cell = row.getCell(0);
                if (cell == null){
                    meg.add("第"+ rowNum + "行第一列为空");
                    continue;
                }
                String cellValue = cell.getStringCellValue();
                if (StringUtils.isEmpty(cellValue)) {
                    meg.add("第"+ rowNum + "行第一列数据为空");
                    continue;
                }

                // 7 判断列是否存在，存在获取列的数据
                EduSubject subject = this.selectSubjectByName(cellValue);
                String pid = null;
                // 8 把这个第一列中的数据（一级分类）保存到数据库中
                if (subject == null){
                    // 9 在保存之前判断此一级分类是否存在，如果存在，不再添加了，如果不存在再补充
                    EduSubject su = new EduSubject();
                    su.setTitle(cellValue);
                    su.setParentId("0");
                    su.setSort(0);
                    baseMapper.insert(su);
                    pid = su.getId();
                }else{
                    pid = subject.getId();
                }
                // 10 在获取每一行的第二列
                Cell cell1 = row.getCell(1);
                // 11 获取第二列中的数据（二级分类）
                if (cell1 == null){
                    meg.add("第"+ rowNum + "行第二列为空");
                    continue;
                }
                String stringCellValue = cell1.getStringCellValue();
                if (StringUtils.isEmpty(stringCellValue)){
                    meg.add("第"+ rowNum + "行第二列数据为空");
                    continue;
                }
                // 12 判断此一级分类中是否存在此二级分类
                EduSubject subject2 = this.selectSubjectByNameAndParentId(stringCellValue, pid);
                // 13 如果此一级分类中有此二级分类
                if (subject2 == null){
                    // 14 如果没有保存二级分类
                    EduSubject su = new EduSubject();
                    su.setTitle(stringCellValue);
                    su.setParentId(pid);
                    su.setSort(0);
                    baseMapper.insert(su);
                }
            }



        } catch (IOException e) {
            e.printStackTrace();
        }
        return meg;
    }



    /**
     * 根据二级分类名称和ParentId查询是否存在subject
     *
     * @param stringCellValue
     * @param pid
     * @return
     */
    private EduSubject selectSubjectByNameAndParentId(String stringCellValue, String pid) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",stringCellValue);
        wrapper.eq("parent_id", pid);
        EduSubject subject = baseMapper.selectOne(wrapper);
        return subject;
    }

    /**
     * 根据课程一级分类查询是否存在
     *
     * @param cellValue
     * @return
     */
    private EduSubject selectSubjectByName(String cellValue) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",cellValue);
        wrapper.eq("parent_id", 0);
        EduSubject subject = baseMapper.selectOne(wrapper);
        return subject;
    }

    /**
     * 树桩数据
     *
     * @return
     */
    @Override
    public List<OneSubject> getTree() {

        List<OneSubject> oneSubjectList = new ArrayList<>();
        //1、把一级分类查询出来、并查询一级分类下的二级分类
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",0);
        List<EduSubject> list = baseMapper.selectList(wrapper);
        for (EduSubject subject1 : list) {
            OneSubject os = new OneSubject();
            BeanUtils.copyProperties(subject1,os);
            //查询下级列表
            QueryWrapper<EduSubject> wr = new QueryWrapper<>();
            wr.eq("parent_id",os.getId());
            List<EduSubject> twoList = baseMapper.selectList(wr);
            for (EduSubject subject2 : twoList) {
                TwoSubject ts = new TwoSubject();
                //复制
                BeanUtils.copyProperties(subject2,ts);
                os.getChildren().add(ts);
            }
            //添加到OneSubject集合中
            oneSubjectList.add(os);
        }

        return oneSubjectList;

    }

    /**
     * 删除一级分类课程
     *
     * @param id
     * @return
     */
    @Override
    public boolean deleteById(String id) {

        // 根据Id查询数据库中是否存在此Id为parent——id（二级分类）
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        List<EduSubject> subjectList = baseMapper.selectList(wrapper);
        //如果有，返回false
        if (subjectList.size() != 0){
            return false;
        }
        int i = baseMapper.deleteById(id);
        //如果没有，直接删除，并且返回true
        return i == 1;
    }

    /**
     * 一级分类
     * @param subject
     * @return
     */
    @Override
    public Boolean saveLevelOne(EduSubject subject) {

        //1 根据这个title判断一下这个一级分类是否存在
        EduSubject eduSubject = this.selectSubjectByName(subject.getId());
        // 存在直接返回false
        if (eduSubject != null){
            return false;
        }
        // 不存在直接返回true
        subject.setSort(0);
        int insert = baseMapper.insert(subject);
        return insert == 1;
    }

    /**
     * 二级分类
     *
     * @param subject
     * @return
     */
    @Override
    public Boolean saveLevelTwo(EduSubject subject) {

        //判断此一级分类中是否存在此二级分类title
        EduSubject sub = this.selectSubjectByNameAndParentId(subject.getTitle(), subject.getParentId());
        if (sub != null){
            //存在
            return false;
        }
        int insert = baseMapper.insert(subject);
        return insert == 1;
    }

}
